package com.example.zmj.qos.rabbitmqDemo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;


/**
 * 消费者
 * Created by ZMJ on 2019/12/25.
 * qos 必须手动ACK
 */
@Component
@RabbitListener(queues = "TestDirectQueue")//监听的队列名称 TestDirectQueue
public class DirectReceiver implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        MessageProperties messageProperties = message.getMessageProperties();

        // 代表投递的标识符，唯一标识了当前信道上的投递，通过 deliveryTag ，消费者就可以告诉 RabbitMQ 确认收到了当前消息，见下面的方法
        long deliveryTag = messageProperties.getDeliveryTag();

        // 如果是重复投递的消息，redelivered 为 true
        Boolean redelivered = messageProperties.getRedelivered();

        // 获取生产者发送的原始消息
        JSONObject jsonObject = JSON.parseObject(new String(message.getBody()));
        System.out.println("消费者收到消息:consume message = " +
                 JSON.toJSONString(jsonObject) + " , deliveryTag = " + deliveryTag + " , redelivered = " + redelivered);

        String messageData = jsonObject.get("messageData").toString();
        System.out.println("消费者收到消息:consume messageData=" + messageData + ", message = " +
                JSON.toJSONString(jsonObject) + " , deliveryTag = " + deliveryTag + " , redelivered = " + redelivered);

        // Qos messageData 等于1或者3的时候不ack 造成阻塞
        if ("1".equals(messageData) || "3".equals(messageData)) {
            // 模拟如果是第一次投递就重回队列
            // Qos messageData 等于1或者3的时候不ack 造成阻塞
        } else {
            // 代表消费者确认收到当前消息，第二个参数表示一次是否 ack 多条消息
            channel.basicAck(deliveryTag, false);
        }

    }



}


